import Vue from 'vue'
import Router from 'vue-router'
import { getToken } from '@/utils/auth'
Vue.use(Router)

import Layout from '@/layout'

export const constantRoutes = [
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    meta: { title: '首页', icon: 'dashboard' },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/sale'),
        meta: { title: '首页', icon: 'dashboard' }
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index'),
    hidden: true
  },
  {
    path: '/mobile/company',
    name:'mobileCompany',
    component: () => import('@/views/mobile/company'),
    hidden: true,
  },
  {
    path: '/follow',
    name:'follow',
    component: Layout,
    redirect: '/index',
    children: [
      {
        path: 'index',
        name: 'followIndex',
        component: () => import('@/views/follow/index'),
        meta: { title: '跟进记录' },
        hidden: true,
      }
    ]
  },
]

const createRouter = () =>
  new Router({
    mode: 'history', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
  })

const router = createRouter()

// 全局拦截
router.beforeEach((to, from, next) => {
  if (to.name === 'Login' || to.name === 'mobileCompany') {
    next()
  } else {
    if (getToken()) {
      // 已登录
      next()
    } else {
      next('/login')
    }
  }
})
router.afterEach((to,from) => {
  let _this = this;
  
})

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
